<template>
  <div style="margin-bottom: 20px;">
    <div class="sku">
      <Card :bordered="false">
        <p slot="title">
          <span v-show="!isAuditing">添加SKU</span>
          <span v-show="isAuditing">审核SKU</span>
          <Tooltip content="SKU是指实际购买的商品，至少有一个SKU" placement="right">
            <span class="tip"><Icon type="help-circled"></Icon></span>
          </Tooltip>
        </p>
        <div slot="extra" v-show="isAuditing && notChange">
          <RadioGroup v-model="discountType" @on-change="radioChange">
            <Radio label="1">sku商品批量折扣</Radio>
            <poptip placement="bottom" trigger="hover">
              <span style="margin-right: 8px;margin-top: 4px;cursor:pointer;">
                <Icon type="help-circled" color="#80848f" size="20"></Icon>
              </span>
              <div slot="content">
                <ul>
                  <li v-for="setup in setupData" :key="setup.id">{{setup.name}}：{{setup.branchDiscount}}%</li>
                </ul>
              </div>
            </poptip>
            <Radio label="2">sku商品指定价格</Radio>
            <Radio label="3">sku商品一口价</Radio>
          </RadioGroup>
        </div>
        <sku-tab ref="skuTab" @deleteImg="deleteBlobImg" v-if="!isAuditing"></sku-tab>
        <price-tab ref="priceTab" v-show="isAuditing"></price-tab>
        <Form :model="skuForm" :label-width="80" label-position="left" ref="skuForm" :rules="skuFormRule">
          <Row>
            <i-col span="6">
              <div class="goodsPhoto">
                <span class="title">SKU图片</span>
                <Upload
                  :show-upload-list="true"
                  :format="['jpg','jpeg','png']"
                  :max-size="2048"
                  :on-format-error="handleFormatError"
                  :on-exceeded-size="handleMaxSize"
                  :before-upload="handleBeforeUpload"
                  action="#">
                  <div style="width: 100px;height:100px;line-height: 100px;position: relative;">
                    <Icon type="camera" size="20"></Icon>
                    <div class="img" v-if="skuImg !== ''">
                      <img :src="skuImg" alt="" width="100" height="100" style="display: block;"/>
                      <div class="upload-list-cover">
                        <Icon type="ios-loop-strong"></Icon>
                      </div>
                    </div>
                  </div>
                </Upload>
              </div>
            </i-col>
            <i-col span="8" style="margin-top: 35px;">
              <FormItem label="SKU名称" prop="goodsSkuName">
                <Input v-model="skuForm.goodsSkuName" style="width: 200px;" placeholder="对应商品属性，比如对应颜色就是红色，蓝色..." />
              </FormItem>
            </i-col>
            <i-col span="8" style="margin-top: 35px;">
              <FormItem label="SKU权重" prop="sortWeight">
                <InputNumber :min="0" :max="10" v-model="skuForm.sortWeight"/>
                <Tooltip content="输入1~10表示商品权重，越大越靠前" placement="right">
                  <span class="tip"><Icon type="help-circled"></Icon></span>
                </Tooltip>
              </FormItem>
            </i-col>
          </Row>
        </Form>
        <div style="text-align: center;margin-bottom: 10px;">
          <Button type="primary" @click="createSku">增加SKU</Button>
        </div>
      </Card>
    </div>
  </div>
</template>

<script>
import skuTab from './skuTab'
import priceTab from './priceTab'
export default {
  name: 'goods-sku',
  data () {
    return {
      url: {
        priceUrl: '/discount/setup/manage/select/all/branch/customer'
      },
      isAuditing: false,
      skuForm: {
        goodsSkuName: '',
        sortWeight: 0
      },
      discountType: '1',
      // 当前添加的sku的图片
      skuImg: '',
      skuImgBlob: null,
      skuImgs: [],
      skuData: {
        data: []
      },
      skuImgData: [], // 图片base64数据用于显示已添加的商品
      // 表单验证
      skuFormRule: {
        goodsSkuName: [
          { required: true, message: '商品属性名不能为空', trigger: 'blur' }
        ]
      },
      setupData: [],
      notChange: true
    }
  },
  methods: {
    setInitData (data) {
      this.isAuditing = true
      if (!data.isChange) {
        data.gsInfoEcho.forEach(item => {
          item.belong = '1'
        })
      }
      this.$refs.priceTab.initSkuData(data)
    },
    radioChange (val) {
      // console.log(val)
      this.$refs.priceTab.setColData(val)
    },
    getSkuData () {
      this.$refs.skuForm.validate((valid) => {
        if (valid) {
          this.createSku()
        }
      })
      let data = this.$refs.skuTab.getSkuData()
      if (!data[0]) {
        return null
      }
      this.skuData.data = data
      return this.skuData
    },
    // 审核返回数据方法
    getSubData () {
      let params = this.$refs.priceTab.getPriceData()
      params.first.forEach(item => {
        if (item.goodsPriceSetups) {
          delete item.goodsPriceSetups
        }
      })
      params.third.forEach(item => {
        if (item.goodsPriceSetups) {
          delete item.goodsPriceSetups
        }
      })
      for (let i in params) {
        if (i !== 'priceTypeInfoDtos') {
          let is = this.doIsEmpty(params[i])
          if (is) {
            return null
          }
        }
      }
      return params
    },
    // 判断价格是否为空方法
    doIsEmpty (arr) {
      let isEm = false
      arr.forEach(item => {
        if (item.retailPrice === null || item.costPrice === null) {
          isEm = true
          return
        } else {
          item.retailPrice *= 100
          item.costPrice *= 100
        }
        if (item.skuStockType === 3 && (item.stock === null || item.warningStock === null)) {
          !item.stock && (item.stock = 0)
          !item.warningStock && (item.warningStock = 0)
        } else if (item.skuStockType !== 3 && (item.stock === null || item.warningStock === null)) {
          isEm = true
          return
        }
        if (item.goodsPriceSetups) {
          item.goodsPriceSetups.forEach(p => {
            if (p.price === null) {
              isEm = true
            } else {
              p.price *= 100
            }
          })
        }
      })
      return isEm
    },
    deleteBlobImg (i) {
      this.skuData.skuImages.sort((a, b) => {
        return b.sortWeight - a.sortWeight
      })
      this.skuData.skuImages.splice(i, 1)
    },
    createSku () {
      this.$refs.skuForm.validate((valid) => {
        if (valid) {
          if (this.skuImg !== '') {
            let isDouble = false
            this.skuData.data.forEach(item => {
              if (item.goodsSkuName === this.skuForm.goodsSkuName) {
                this.$Message.error('sku名称不能重复')
                this.skuForm.goodsSkuName = ''
                isDouble = true
              }
            })
            if (isDouble) {
              return
            }
            this.skuImgs.push({
              img: this.skuImgBlob,
              sortWeight: this.skuForm.sortWeight
            })
            this.skuData.data.push({
              ...(this.skuForm),
              img: this.skuImg
            })
            this.skuData.skuImages = this.skuImgs
            // console.log(this.isAuditing)
            if (this.isAuditing) {
              let data = {
                imgBlob: this.skuImgBlob,
                ...(this.skuForm),
                img: this.skuImg
              }
              this.$refs.priceTab.getAddSku(data, this.goodsId)
            } else {
              this.$refs.skuTab.changeData(this.skuData.data)
              this.$Message.success('预添加成功，最后记得点创建按钮')
            }
            this.$refs.skuForm.resetFields()
            this.skuImg = ''
          } else {
            this.$Message.error('必须要有图片')
          }
        } else {
          this.$Message.error('所有输入框都不允许为空')
        }
      })
    },
    setImgData (data, blob) {
      this.skuImg = data
      this.skuImgBlob = blob
      this.skuImgData.push(data)
    },
    // 文件格式不是图片时提醒
    handleFormatError () {
      this.$Message.error('必须要是图片(jpg,jpeg,png)格式')
    },
    // 图片超出大小时提醒
    handleMaxSize () {
      this.$Message.error('图片太大了，我受不了了')
    },
    // 上传图片前触发，阻止上传进入切图操作
    handleBeforeUpload (e) {
      let skuE = {
        e,
        name: 'sku'
      }
      this.$emit('setImage', skuE)
      return false
    }
  },
  props: ['goodsId'],
  created () {
    this.$ajax.get(this.url.priceUrl).then(res => {
      this.setupData = res.data.data
    })
  },
  components: {
    skuTab,
    priceTab
  },
  mounted () {
    // this.$refs.priceTab.initSkuData(this.initSkuData)
    if (this.$route.query.change) {
      this.notChange = false
    }
  }
}
</script>

<style scoped>
  .goodsPhoto .title{
    line-height: 100px;
    font-size: 12px;
    font-weight: 800;
    margin-right: 20px;
    float: left;
  }
  .ivu-upload{
    display: inline-block;
    width:100px;
    height: 100px;
    text-align: center;
    margin-right: 10px;
    border: 1px solid #ddeed1;
    cursor: pointer;
  }
  .timeImg{
    position: absolute;
    margin-right: 10px;
    padding: 10px;
    right: 0;
    top: 66px;
    width: 28%;
    height: 500px;
    border: 1px solid #dddee1;
    border-radius: 3px;
  }
  .img{
    margin-right: 10px;
    border-radius: 10px;
    position: absolute;
    top: 0;
    left: 0;
    overflow: hidden;
  }
  .upload-list-cover{
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0,0,0,.6);
    text-align: center;
  }
  .img:hover .upload-list-cover{
    display: block;
  }
  .upload-list-cover i{
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 45px 5px 0 0;
  }
  .sku{
    padding: 4px;
    background-color: #eee;
  }
  .tip{
    margin-left: 8px;
    font-size: 18px;
    color: #80848f;
    cursor: pointer;
  }
</style>
